package cn.springsoter.core.tool.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

/**
 * 基于盐加密工具类
 * 
 * @author kevin
 *
 */
public class EncryptionSaltUtil {
	private static final String HEX_NUMS_STR = "0123456789abcdef";
	private static String DEFAULT_ENCODING = "UTF-8";
	private static String MD5 = "MD5";

	private EncryptionSaltUtil() {
	}

	/**
	 * 验证口令是否合法
	 * 
	 * @param password
	 * @param passwordInDb
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static boolean validPassword(String password, String passwordInDb, String salt)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		String digest = getEncryptedPwd(password, salt);
		if (StringUtils.equals(digest, passwordInDb)) {
			// 口令正确返回口令匹配消息
			return true;
		} else {
			// 口令不正确返回口令不匹配消息
			return false;
		}
	}

	/**
	 * 获得加密后的16进制形式口令
	 * 
	 * @param password
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	public static String getEncryptedPwd(String password, String salt)
			throws NoSuchAlgorithmException, UnsupportedEncodingException {
		// 声明消息摘要对象
		MessageDigest md = null;
		// 创建消息摘要
		md = MessageDigest.getInstance(MD5);
		// 将盐数据传入消息摘要对象
		md.update(salt.getBytes(DEFAULT_ENCODING));
		// 将口令的数据传给消息摘要对象
		md.update(password.getBytes(DEFAULT_ENCODING));
		// 获得消息摘要的字节数组
		byte[] digest = md.digest();
		return byteToHexString(digest);
	}

	/**
	 * 获取加盐字符串，默认是uuid
	 * 
	 * @return
	 */
	public static String getSaltStr() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	/**
	 * 将16进制字符串转换成字节数组
	 * 
	 * @param hex
	 * @return
	 */
	public static byte[] hexStringToByte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] hexChars = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
		}
		return result;
	}

	/**
	 * 将指定byte数组转换成16进制字符串
	 * 
	 * @param b
	 * @return
	 */
	public static String byteToHexString(byte[] b) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexString.append(hex.toLowerCase());
		}
		return hexString.toString();
	}
}
